package com.redstars.generate.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.redstars.generate.page.PageResult;
import com.redstars.generate.query.Query;
import lombok.Builder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : zhouhx
 * @date : 2022/10/5 15:12
 */
public class PageUtils<T> {
    /* *
     * 默认页码
     */
    private static final int DEFAULTPAGENO =1;
    /* *
     * 默认显示条数
     */
    private static final int DEFAULTPAGESIZE =20;

    /* *
     *
     * @author zhuohx
     * @description 生成分页对象
     * @parms  [query]
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<T>
     * @throws
     * @date 2022/9/19 9:49
     */
    public  IPage<T> getPage(Query query) {
        int pageNo = ObjectUtil.isEmpty(query.getPage())?DEFAULTPAGENO:query.getPage();
        int pageSize = ObjectUtil.isEmpty(query.getLimit())?DEFAULTPAGESIZE:query.getLimit();
        Page<T> page = new Page<>(pageNo, pageSize);

        // 排序
        if(StringUtils.isNotBlank(query.getOrder())){
            if(query.isAsc()) {
                return page.addOrder(OrderItem.asc(query.getOrder()));
            }else {
                return page.addOrder(OrderItem.desc(query.getOrder()));
            }
        }

        return page;
    }


    public <T> PageResult<T> getPageData(IPage page, Class<T> target){
        List<T> targetList = BeanUtil.copyToList(page.getRecords(), target);
        return new PageResult<>(page, targetList);
    }
}
